<?php
use GatewayClient\Gateway;

class controller_autogames extends model_autogames
{
    # region 自动 - 发包
    public function autogameover_add()
    {

        $gameid = $this->existsKeyInArray('gameid', $_GET, 'N');
        # 检测当前玩法是否开放自动发包

        $sql = "";
        # 统计房间的红包数
        $sql = "SELECT g.id,IFNULL(count1,0) AS count,g.title FROM `@@games` g LEFT JOIN (SELECT l.gameid,COUNT(1) AS count1 FROM `@@bets` l WHERE (l.`overtime` - (UNIX_TIMESTAMP() - l.`begintimes`)) > 0 AND l.`state`=0 GROUP BY l.`gameid`) t1 ON t1.gameid=g.id";
        $gameCount = $this->db->query($sql,3);
        foreach ($gameCount as $key=>$v)
        {
            if($v['count']==0) {
                $result = $this->mod_autosend_togame($v['id']);
                if ($result['state'] == 200) {
                    $beforResult = array(
                        'state' => 200,
                        'cmd' => 'newred',
                        'gameid' => $result['gameid'],
                        'datas' => $result['datas'],
                    );
                    Gateway::sendToGroup($result['groupname'], json_encode($beforResult));
                }
                echo json_encode(array(
                    'state' => 200,
                    'msg' => '正在发【'.$v['title'].'】包'
                ));
                //sleep(5);
            }
        }


    }
    public function autosendgame()
    {
        exit(array(
            'state' => 200,
            'msg' => '本过程已失效',
        ));

        $gameid = $this->existsKeyInArray('gameid', $_GET, 'N');
        # 检测当前玩法是否开放自动抢包

        if(empty($gameid)) core::error('gameid is error');
        # 统计房间的红包数
        $sql = "SELECT gameid,COUNT(1) AS count FROM `@@bets` WHERE (`overtime` - (UNIX_TIMESTAMP() - `begintimes`)) > 0 AND `state`=0 AND `gameid`=".$gameid;
        $gameCount = $this->db->query($sql,2);
        $maxcount = mt_rand(2, 5);
        if($gameCount['count']>=$maxcount) exit(json_encode(array('state'=>404,'msg'=>'当前已有'.$maxcount.'个以上红包，本次操作无效……')));

        $result = $this->mod_autosend_togame($gameid);
        //var_dump($result);
        if ($result['state'] == 200) {
            $beforResult = array(
                'state' => 200,
                'cmd' => 'newred',
                'gameid' => $result['gameid'],
                'datas' => $result['datas'],
            );
            echo json_encode(array(
                'state' => 200,
                'msg' => '【'.$this->formatTimes(time()).'】【'.$result['user']['uno'].' - '.$result['user']['nickname'].'】正在发【'.$gameid,'】包',
            ));
            Gateway::sendToGroup($result['groupname'], json_encode($beforResult));
        }else{
            echo json_encode(array(
                'state' => 404,
                'msg' => '【'.$this->formatTimes(time()).'】发【'.$gameid.'】包错误！',
            ));
        }

    }
    # endregion

    # region 自动 - 抢包
    public function autograb()
    {
        exit(array(
            'state' => 200,
            'msg' => '本过程已失效',
        ));

        $gameid = $this->existsKeyInArray('gameid', $_GET, 'N');
        if (empty($gameid)) exit(json_encode(array('state'=>404,'msg'=>'游戏参数不正确')));
        # 找出正在进行的红包的类型及用户类型（红包种类）
        $red = $this->mod_autogrob($gameid);
        if (!$red) exit(json_encode(array('state'=>404,'msg'=>'【游戏 game_'.$gameid.'】红包不存在')));
        # 找出除发包玩家的所有余额足够的用户列表，自动登录并开始抢包
        $user = $this->mod_autogrobuser($red);
        if (!$user) exit(json_encode(array('state'=>404,'msg'=>'没有适合操作的玩家')));
        $args = array(
            'cmd' => 'grab',
            'room_id' => 'game_' . $red['gameid'],
            'game_id' => intval($red['gameid']),
            'red_issue' => $red['issue'],
            'pass' => '',
            'token' => $user['webtoken'],
        );
        $url = str_replace('https://', 'http://', $this->config['apiurl']) . '/game/grabgameenvelopes?';
        $url .= 'cmd=' . $args['cmd'];
        $url .= '&room_id=' . $args['room_id'];
        $url .= '&game_id=' . $args['game_id'];
        $url .= '&red_issue=' . $args['red_issue'];
        $url .= '&pass=';
        $url .= '&token=' . $args['token'];
        //初始化
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        //打印获得的数据
        //var_dump($output);

        if (strtolower($output) != 'null') {
            $data = json_decode($output, true);
            if (isset($data['state']) && count($data) > 0 AND $data['state'] == 200) {
                # 通知玩法房间更新当期红包更新数据人数
                if (isset($data['updatered'])) {
                    $data['updatered']['state'] = 200;
                    Gateway::sendToGroup($data['groupname'], json_encode($data['updatered']));
                }
                # 通知当前期数房间有新玩家加入抢包
                if (isset($data['newsjoingrab'])) {
                    // Gateway::joinGroup($client_id, $data['reddata']['issue']);
                    Gateway::sendToGroup($data['reddata']['issue'], json_encode($data['newsjoingrab']));
                }
                //组织当前玩家的展示页面数据
                //Gateway::sendToCurrentClient(json_encode($data['curdata']));

                $data['datas'] = $data['reddata'];
                unset($data['reddata']);
                unset($data['updatered']);
                unset($data['newsjoingrab']);
                //unset($data['room_name']);
                $settlement = (isset($data['settlement']) ? $data['settlement'] : false);
                unset($data['settlement']);
                # 通知当前玩家打开抢包页面，列出抢包用户
                // Gateway::sendToCurrentClient(json_encode($data));
                # 通知小组玩家结算
                if ($settlement && isset($settlement['issue'])) {
                    //print_r($settlement);
                    Gateway::sendToGroup($settlement['issue'], json_encode($settlement));
                    /*
                    # 如果结束当期红包，将要通知参与的用户更新相应的玩家余额
                    if (isset($settlement['userscoin']) && is_array($settlement['userscoin'])) {
                        foreach ($settlement['userscoin'] as $k => $v) {
                            Gateway::sendToUid('P' . $k, json_encode(array(
                                'usercoin' => $v['coin'],
                                'userscore' => intval($v['score']),
                                'state' => 200,
                                'cmd' => 'updateusercoin',
                            )));
                        }
                    }
                    # 处理跑马灯内容
                    $marquee = array(
                        'cmd' => 'marquee',
                        'state' => 200
                    );
                    if (isset($settlement['room_name'])) {
                        $gameid = str_replace('game_', '', $settlement['room_name']);
                        $gamename = $this->mod_getGameForID($gameid);
                        $gamename = isset($gamename['title']) ? $gamename['title'] : '';

                        foreach ($settlement['grabusers'] as $k => $v) {
                            if ($v['profit'] > 0) {
                                switch ($v['cardtitle']) {
                                    case '2倍':
                                    case '1.5倍':
                                    case '1倍':
                                    case '比大小':
                                        $v['cardtitle'] = '';
                                        break;
                                    default:
                                        break;
                                }
                                $marquee['datas'][$k] = array(
                                    'title' => $gamename,
                                    'nickname' => $v['nickname'],
                                    'avatar' => $v['avatar'],
                                    'profit' => $v['profit'],
                                    'cardtitle' => $v['cardtitle'],
                                );
                            }
                        }
                        //print_r($settlement);
                        #保存跑马灯的内容
                        $this->redisSetEx($settlement['room_name'], $marquee, 600);
                        $this->redisSetEx('games_marquee_0', $marquee, 600);

                        Gateway::sendToGroup($settlement['room_name'], json_encode($marquee));
                        Gateway::sendToGroup('public', json_encode($marquee));
                    }
                    */
                }
                $grab_cur_user = $data['user'];
                echo json_encode(array(
                    'state' => 200,
                    'msg' => '【'.$this->formatTimes(time()).'】'.$grab_cur_user['nickname'].'【'.$grab_cur_user['uno'].'】抢【'.$data['datas']['issue'].'】包成功',
                    'settlement' => $settlement,
                ));
            }
        } else {
            echo json_encode(array(
                'state' => 404,
                'msg' => '抢包失败',
            ));
        }
    }
    # endregion

    # region 自动 - 处理超时
    public function autogameover()
    {
        echo json_encode(array('state'=>404,'msgid'=>404,'msg'=>'当前操作无效'));
        /*
        $sql = "SELECT `id`,`issue`,`gameid`,`need` FROM `@@bets` WHERE (`overtime` - (UNIX_TIMESTAMP() - `begintimes`)) < -110 AND `state`=0 AND `need`>`cur` ORDER BY `id` ASC LIMIT 1";
        $data = $this->db->query($sql,2);

        $issue = $data['issue'];
        $gameid = $data['gameid'];
        $need = $data['need'];

        if(empty($issue))
        {
            echo json_encode(array(
                'state' => 404,
                'msg' => "【".date('Y-m-d H:i:s', time())."】没有找到需要超时处理的红包",
            ));
            exit;
        }

        $url = str_replace('https://','http://',$this->config['apiurl']).'/game/gametimeout?';
        $url .= 'red_issue='.$issue;
        //初始化
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        //打印获得的数据

        if(strtolower($output)!='null') {
            $data = json_decode($output, true);
            if(count($data)>0 && $data['state']!=404) {
                Gateway::sendToGroup('game_'.$gameid, array(
                    'cmd'=>'updatered',
                    'state' => 200,
                    'issue' => $issue,
                    'cur' => $need,
                ));
                if(isset($data['timeoutdata'])){
                    echo json_encode(array(
                        'state' => 200,
                        'msg' => "第{$data['timeoutdata']['issue']}期红包参与人数不足超时取消成功！",
                    ));
                }
            }else{
                //$this->db->transaction('begin');
                //$sql = "UPDATE `@@bets` SET `isauto`=`isauto`+1 WHERE `issue`='".$issue."' LIMIT 1";
                //$this->db->query($sql,1);
                //$this->db->transaction('commit');
                echo json_encode(array(
                    'state' => 404,
                    'msg' => $issue."超时退回-操作失败(1)",
                    'output' => $output,
                ));
            }
        }else{
            echo json_encode(array(
                'state' => 404,
                'msg' => $issue."超时退回-操作失败(2)",
                'output' => $output,
            ));
        }
    */
    }
    # endregion
}